package extent;

import android.os.AsyncTask;

import com.dzeshko.http.HttpManager;

public abstract class CommonAsyncTask<T> extends
		AsyncTask<java.lang.String, java.lang.Void, T> {

	private ParamCallback<T> mParamCallback;

	public CommonAsyncTask(ParamCallback<T> paramCallback) {
		super();
		this.mParamCallback = paramCallback;
	}

	private Exception e;

	@Override
	protected T doInBackground(String... params) {
		try {
			String source = HttpManager.getInstance().loadAsString(params[0]);
			return convert(source);
		} catch (Exception e) {
			this.e = e;
		}
		return null;
	}

	public abstract T convert(String source) throws Exception;

	@Override
	protected void onPostExecute(T result) {
		super.onPostExecute(result);
		if (e != null) {
			mParamCallback.onError(e);
		} else {
			mParamCallback.onSuccess(result);
		}
	}

	public void start(String... params) {
		execute(params);

		// TODO HW: if (API > 10) executeOnExecutor
	}
}
